#!/usr/bin/env python

import csv, sys, os, datetime

COLOR    = "green"
TEST     = "cf"

MACHINE   = os.environ["MACHINE"]
XYMONHOME = os.environ["XYMONHOME"]

filename = XYMONHOME+'/tmp/cf_lastseen.csv'

YM = ""
RM = "" 
T = "" 
T0="Peers as last seen by "+MACHINE+" :\n<TABLE border=1 cellpadding=5><TR><TD>Host</TD><TD>IP</TD><TD>Not seen for (min)</TD><TD>Not seen Avg(min)</TD></TR>\n"
T1="</TABLE>\n"

def xymon_rep(color,l0):
  TEST    = "cf"
  XYMON  = os.environ["XYMON"]
  XYMSRV = os.environ["XYMSRV"]
  # Report status to the xymon server
  LINE = 'status '+MACHINE+'.'+TEST+' '+COLOR+' Cfengine status \n'+L0
  cmd = XYMON+' '+XYMSRV+' "'+LINE+'"'
  os.system(cmd)
  exit(0)


with open(filename, 'rb') as f:
  reader = csv.reader(f)
  try:
    for row in reader:
       dir = row[0]
       if dir == '+':
        dir = 'out'
       elif dir == '-':
        dir = 'in'
       host = row[2].lstrip().split('.')[0]
       ip = row[3].lstrip()
       notseen = row[5].lstrip()
       notseenavg = float(row[6].lstrip())*60
       notseenmin = float(notseen)*60
       T += "<TR><TD>"+host+"("+dir+")"+"</TD><TD>"+ip+"</TD><TD>"+str(notseenmin)+"</TD><TD>"+str(notseenavg)+"</TD></TR>\n<!--\n"+host+"_"+dir+" : "+str(notseenavg)+"\n-->\n"     
       if notseenavg > 10:
        COLOR = "red"
        YM += '<B>'+host+'('+dir+')  \t- Not seen for '+str(notseenavg)+' minutes(avg)</B>\n'
  except csv.Error, e:
    sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))

L0= '\n<HR>'+YM+'\n<HR>\n\n'+T0+T+T1

xymon_rep(COLOR,L0)
